﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using Microsoft.SharePoint;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Data.SqlClient;

namespace WebCumpleanios
{
    public partial class frmPlantilla1 : System.Web.UI.Page
    {
        String _usuario = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _usuario = Utils.Base64Decode( Request.QueryString["id"]);
                ViewState["user"] = _usuario;
                String _plant1 = ConfigurationManager.AppSettings["plantilla1"].ToString();
                String _plant2 = ConfigurationManager.AppSettings["plantilla2"].ToString();
                String _plant3 = ConfigurationManager.AppSettings["plantilla3"].ToString();
                String _plant4 = ConfigurationManager.AppSettings["plantilla4"].ToString();

                if (!_plant1.Equals(""))
                    if (archivoExiste(_plant1))
                        ImageButton1.ImageUrl = _plant1;
                if (!_plant2.Equals(""))
                    if (archivoExiste(_plant2))
                        ImageButton2.ImageUrl = _plant2;
                if (!_plant3.Equals(""))
                    if (archivoExiste(_plant3))
                        ImageButton3.ImageUrl = _plant3;
                if (!_plant4.Equals(""))
                    if (archivoExiste(_plant4))
                        ImageButton4.ImageUrl = _plant4;
            }
        }

        private Boolean archivoExiste(String _file)
        {
            Boolean _resp = false;
            _resp = File.Exists(Server.MapPath(_file));
            return _resp;
        }

        private String obtenerFoto(String user)
        {
            SPWeb _web = obtenerWeb(ConfigurationManager.AppSettings["urlSite"].ToString());
            SPPictureLibrary libreriaImagenes = (SPPictureLibrary)_web.Lists[ConfigurationManager.AppSettings["lstFotos"].ToString()];
            String _urlImagen = "";
            DataTable _dt = libreriaImagenes.Items.GetDataTable();
            DataRow[] _rows = _dt.Select("NameOrTitle like '" + user.ToLower() + ".%'", "");
            String _name = string.Empty;
            byte[] archivo = null;

            if (_rows.Length > 0)
            {
                _name = _rows[0]["NameOrTitle"] + "";
                SPListItem _item = libreriaImagenes.Items.GetItemById(int.Parse(_rows[0]["ID"] + ""));
                archivo = _item.File.OpenBinary();
            }
            else
            {
                _name = user.ToLower();
                archivo = File.ReadAllBytes(Server.MapPath(@"images\camera.png"));
            }

            MemoryStream theMemStream = new MemoryStream();
            theMemStream.Write(archivo, 0, archivo.Length);
            _urlImagen = Server.MapPath(@"IMAGENES\F" + _name);

            SaveMemoryStream(theMemStream, _urlImagen);

            return _urlImagen;
        }

        public static void SaveMemoryStream(MemoryStream ms, string FileName)
        {
            if (!File.Exists(FileName))
            {
                FileStream outStream = File.OpenWrite(FileName);
                ms.WriteTo(outStream);
                outStream.Flush();
                outStream.Close();
            }
            
        }

        public static MemoryStream Mezcla(Stream imagenOrigen, Stream imagenSuperpuesta, double anchorelativo, double altorelativo, double posrelativaX, double posrelativaY, bool relativo)
        {
            // Convierte a image el fichero original y el que vamos a superponer
            System.Drawing.Image original = System.Drawing.Image.FromStream(imagenOrigen);
            System.Drawing.Image superpuesta = System.Drawing.Image.FromStream(imagenSuperpuesta);

            // Decidimos las dimensiones en base a si son relativas o absolutas
            double posicionX;
            double posicionY;
            double ancho;
            double alto;

            if (relativo)
            {
                posicionX = posrelativaX * original.Width;
                posicionY = posrelativaY * original.Height;
                ancho = anchorelativo * original.Width;
                alto = altorelativo * original.Height;
            }
            else
            {
                posicionX = posrelativaX;
                posicionY = posrelativaY;
                ancho = anchorelativo;
                alto = altorelativo;
            }

            // A mezclar se ha dicho
            System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(imagenOrigen);
            Bitmap bmPhoto = new Bitmap(original.Width, original.Height, PixelFormat.Format24bppRgb);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
            
            Rectangle rec = new Rectangle(0, 0, original.Width, original.Height);
            grPhoto.DrawImage(imgPhoto, rec, rec, GraphicsUnit.Pixel);

            grPhoto.DrawImage(superpuesta, new Rectangle((int)posicionX, (int)posicionY, (int)ancho, (int)alto), new Rectangle(0, 0, superpuesta.Width, superpuesta.Height), GraphicsUnit.Pixel);

            MemoryStream mm = new MemoryStream();
            bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);

            // Cerramos todo lo cerrable

            original.Dispose();
            imgPhoto.Dispose();
            bmPhoto.Dispose();
            grPhoto.Dispose();

            return mm;
        }

        private void crearXML(String user, String _pathprincipal)
        {
            DataTable _dt = new DataTable();
            _dt.TableName = user;
            _dt.Columns.Add("pathTemplate", Type.GetType("System.String"));
            _dt.Columns.Add("pathDate", Type.GetType("System.String"));

            DataRow _newRow = _dt.NewRow();
            _newRow["pathTemplate"] = _pathprincipal;
            _newRow["pathDate"] = _pathprincipal;
            _dt.Rows.Add(_newRow);
            _dt.WriteXml(Server.MapPath(@"XML\" + ViewState["user"].ToString() + ".xml"));
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            guardarImagenFusionada(ConfigurationManager.AppSettings["plantilla1"].ToString());
        }
        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            guardarImagenFusionada(ConfigurationManager.AppSettings["plantilla2"].ToString());
        }
        protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
        {
            guardarImagenFusionada(ConfigurationManager.AppSettings["plantilla3"].ToString());
        }
        protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
        {
            guardarImagenFusionada(ConfigurationManager.AppSettings["plantilla4"].ToString());
        }

        private void guardarImagenFusionada(string URLPlantilla)
        {
            string codigo = ViewState["user"].ToString().Trim();
            string nuevoNombreImagen = codigo + "_" + Guid.NewGuid().ToString() + "_" + DateTime.Now.Year;

            String _plant = URLPlantilla;
            char[] c = { '.' };
            string[] _val = _plant.Split(c);
            String _extension = _val[1];
            if (!_plant.Equals(""))
            {
                if (archivoExiste(_plant))
                {
                    //IMAGEN
                    String _pathFoto = obtenerFoto(ViewState["user"] + "");
                    String _pathFondo = Server.MapPath(@"IMAGENES") + @"\P" + ViewState["user"].ToString() + "." + _extension;
                    File.Copy(Server.MapPath(_plant), _pathFondo);

                    //FUSION DE IMAGENES
                    FileStream original = new FileStream(_pathFondo, FileMode.Open);
                    FileStream superpuesta = new FileStream(_pathFoto, FileMode.Open);
                    MemoryStream mm = Mezcla(original, superpuesta, 150, 220, 425, 215, false);
                    String _pathprincipal = Server.MapPath(@"fla\imagenes\" + nuevoNombreImagen + "." + _extension);
                    SaveMemoryStream(mm, _pathprincipal);
                    original.Dispose();
                    superpuesta.Dispose();
                    File.Delete(_pathFondo);
                    File.Delete(_pathFoto);

                    //XML
                    //crearXML(ViewState["user"].ToString(), _pathprincipal);
                    hdRedirect.Value = ConfigurationManager.AppSettings["enlace2"].ToString() + "?id=" +  Utils.Base64Encode(ViewState["user"].ToString().Trim()) + "&i=" + Utils.Base64Encode(DateTime.Now.Millisecond.ToString());


                    /**/
                    SqlConnection _cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnx1"].ToString());
                    SqlCommand _cmd = new SqlCommand();
                    _cmd.CommandType = CommandType.StoredProcedure;
                    _cmd.Connection = _cnn;
                    _cmd.CommandText = "proc_newNombreImagen";
                    _cmd.Parameters.Add(new SqlParameter("@id", ViewState["user"].ToString().Trim()));
                    _cmd.Parameters.Add(new SqlParameter("@imagen", nuevoNombreImagen));
                    _cnn.Open();
                    _cmd.ExecuteNonQuery();
                    _cnn.Close();

                    /**/
                }
            }

        }

        private SPWeb obtenerWeb(String _siteURL)
        {
            //SPSite _site = new SPSite(_siteURL);
            //SPWeb _web = _site.OpenWeb();
            //SPUser _user = _web.AllUsers[ConfigurationManager.AppSettings["pImpersonalizacion"]];
            //SPUserToken mitoken = _user.UserToken;
            //_site = new SPSite(_siteURL, mitoken);
            //_web = _site.OpenWeb();
            //return _web;
            SPWeb spWeb = null;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite sitio = new SPSite(_siteURL))
                {
                    spWeb = sitio.OpenWeb();
                }
            });

            return spWeb;
        }
    }
}